const { contextBridge, ipcRenderer } = require('electron')

class index {
    constructor() {

        this.levelq
        this.emitEvent()
        this.onEvent()
        this.setting()
        this.sendMessage1()
        this.user = getItem("UserInfo")
        this.ChangeProperties()
        this.fontsty = {
            font: "",
            color: "",
            background: ""
        }
    }
    emitEvent() {
        //向后端发送群成员信息
        sk.emit('text', getItem("UserInfo"));
    }

    renderSystemMessage(text) {
        $(".c_left").append(`
            <li class="system_message">
                <span>${text}</span>
            </li>
        `)
    }

    //接受后端发送的数据
    onEvent() {
        //窗口抖动
        sk.on('ShakeMessage', (data) => {
            if (data.user_name == this.user.user_name) {
                this.renderSystemMessage(`你发送了窗口抖动`)
            } else {
                this.renderSystemMessage(`${data.user_name}给你发送了窗口抖动`)
            }

        })
        //抖动  
        sk.on('openShake', (data) => {

            ipcRenderer.send('windowsShake')
        })
        //禁言
        sk.on('MushinopenShake', (data) => {
            this.Mushinopen()
        })

        sk.on('MushinsocketAll', (data) => {
            this.Mushinopen()
        })
        //加群通知
        sk.on('WelcomeUser', (data) => {
            this.renderSystemMessage(data)
        })
        //
        //群成员
        sk.on('onLineUserList', (data) => {
            console.log("群成员", data)
            $(".c_right .title").text(`群成员 ${data.length}`)
            $(".c_right ul").empty()

            data.forEach(v => {
                $(".c_right ul").append(`
                <li>
                    <div class="use">
                        <img src="${v.user_img}" alt="">
                        <span class="dd">${v.user_name}</span>
                    </div>
                    ${v.level == 3
                        ? ''
                        : `<i class="iconfont icon-yonghu ${v.level == 1 ? 'qz' : 'gly'}"></i>`
                    }
                    
                </li>
               `)
            });
            //获取等级
            console.log("data.level", data[data.length - 1].level)
            this.levelq = data[data.length - 1].level

            let set = this
            //禁言
            $(".use img").click(function () {
                let name = $(this).parent().find(".dd").text()
                console.log("name", name)
                console.log("name5555", set.user.user_name)
                if (name == set.user.user_name) {

                } else {
                    set.user.Mushinname = name
                    sk.emit('Mushinsocket', set.user)
                }


                // console.log(1)

            })
        })

        //获取其他人发送的消息

        sk.on("ServerMessage", data => {
            console.log("获取别人发送的数据", data)
            this.renderMessage(data, 'medd', "s", data.fontsty)

        })
        //获取图片
        sk.on('uploadImgName', data => {
            data.message = `
                <img class="gif_img" src="http://127.0.0.1:3000/upload/${data.message}" alt="">
            `
            this.renderMessage(data, "other", "s", this.fontsty)
        })
    }

    Mushinopen() {
        let index = 60
        $(".input").attr("contenteditable", "false");
        $(".input").addClass("cus");
        console.log("进来了")
        console.log($(".input").removeProp('id'))
        this.renderSystemMessage("你被禁60秒")
        let dd = $(".system_message span").last()
        let jishi = setInterval(() => {
            index -= 1;
            dd.text(`你被禁${index}秒`)
        }, 1000)
        setTimeout(() => {
            $(".input").attr("contenteditable", "");
            $(".input").removeClass("cus");
            dd.text(`你已被解除禁言`)
            clearInterval(jishi)

        }, 60000)

    }

    setting() {
        let set = this
        $(".user img").attr({
            src: getItem("UserInfo").user_img
        })

        $(".user .name").text(getItem("UserInfo").user_name)
        $(".header .room_name").text(getItem("UserInfo").room_id)

        //点击禁言
        $(".icon-jinyan").click(function () {
            sk.emit("Allsilenced",set.user)
        })


        //抖动
        $(".icon-shake").click(function () {
            console.log(1)
            //向后端发送数据
            delete set.user.clickUserName
            sk.emit('socketShake', set.user)
        })



        //图片点击事件
        $(".icon-tupian1").click(async function () {
            let path = await ipcRenderer.invoke('openFileSelect')
            console.log("你选择的文件路径未：", path);
            let Base64url = await imgToBase64(path)
            console.log("imgToBase64：", Base64url);
            set.user.message = `
                <img class="gif_img" src="${path}" alt="">
            `
            set.user.timestamp = timestamp();
            set.renderMessage(set.user, 'me', "gif", set.fontsty)

            sk.emit("uploadFile", {
                user: set.user,
                base64: Base64url,
                fileType: path.match(/\.(\w+)$/)[1]
            })
        })

        //将表情添加到表情
        for (let i = 0; i < 274; i++) {
            $(".emote").append(`
                 <img src="../img/icon/${i}fix@2x.png">
            `)
        }

        //当鼠标移动到表情上
        $(".emote img").hover(function () {
            $(this).attr({
                src: `../img/icon/${$(this).index()}@2x.gif`
            })
        }, function () {
            $(this).attr({
                src: `../img/icon/${$(this).index()}fix@2x.png`
            })
        })
        //将表情添加到输入框
        $(".emote img").click(function () {
            $(".input").append(`
              <img class="emote_img" src="../img/icon/${$(this).index()}@2x.gif" alt="">
            `)
        })


        //添加动图
        for (let i = 0; i <= 12; i++) {
            $(".gif").append(`
                <img class="gif_img" src="../img/gif/${i}.gif" alt="">
            `)
        }

        $(".gif img").click(function () {
            //<img class="gif_img" src="../img/gif/8.gif" alt="">
            console.log($(this).prop("outerHTML"))
            set.user.message = $(this).prop("outerHTML")
            console.log(set.user.message)
            set.user.timestamp = timestamp()
            console.log(set.user)
            set.user.fontsty = set.fontsty
            sk.emit('sendMessage', set.user);
            set.renderMessage(set.user, 'me', 'gif', set.fontsty)
        })

        //图标点击
        $(".f_action i").click(function () {

            if ($(this).index() <= 3) {
                //判断当前是否是显示状态
                if ($(".menu").css("display") == "none") {
                    $(".menu").show()
                    set.changeActive($(".menu_footer li").eq($(this).index()))
                } else {
                    if ($(".menu_footer li").eq($(this).index()).hasClass("active")) {
                        $(".menu").hide()
                    } else {
                        set.changeActive($(".menu_footer li").eq($(this).index()))
                    }
                    //判断点击前面四个

                }


            }
        })
        $(".menu_footer li").click(function () {
            set.changeActive($(this))
        })
    }

    ChangeProperties() {
        let s = this;
        $(".font select").on("change", function () {
            s.fontsty.font = $(".font select").val()
        });

        $(".font input").on("change", function () {

            s.fontsty.color = $(".font input").val()
        });

        $(".back input").on("change", function () {

            s.fontsty.background = $(".back input").val()
        });
    }
    changeActive(el) {
        el.eq($(this).index()).addClass("active").siblings().removeClass("active")

        $(".menu_title").text($(el).text())
        $(".menu_list .menu_item").eq($(el).index()).addClass("active").siblings().removeClass("active")
    }

    sendMessage1() {
        var self = this;
        console.log(0)
        $(".input").keydown(function (event) {
            console.log(1)
            let { keyCode, ctrlKey } = event;
            if (keyCode == 13 && ctrlKey) {
                $(".input").append("<div><br></div>")
                self.moveEnd($(".input")[0], 'end')
                console.log(2)
            } else if (keyCode == 13) {
                console.log(3)
                if ($(".input").html().length != 0) {

                    self.user.message = $(".input").html()
                    self.user.timestamp = timestamp()
                    console.log("self.levelq", self.levelq)
                    self.user.level = self.levelq
                    self.user.fontsty = self.fontsty
                    console.log(4)
                    sk.emit("sendMessage", self.user)
                    self.renderMessage(self.user, 'me', "s", self.fontsty)
                    $(".input").html("")
                    //将我的消息发送到后端
                }
                return false;
            }
        });
    }

    moveEnd(el) {
        el.focus();
        var range = window.getSelection();
        range.selectAllChildren(el);
        range.collapseToEnd();
    }

    renderMessage(v, type, img, sty) {
        let set = this
        console.log("v.timestamp", v.timestamp)
        console.log(v)
        $(".c_left").append(`
        
    <li class="${type == "me" ? 'm_r' : ''} ">
        <div class="time">${format('hh:mm:ss', v.timestamp)}</div>
        <div class="item">
            <img class="avatar" src="${v.user_img}" alt="">
            <div class="text">
                <div class="name">
                ${v.level == 3 ? "" : `<span ${v.level == 1 ? `class="tips_qz" > 群主` : `class="tips_gly">管理员`}</span>`}
                  <lb class="u_n">${v.user_name}</lb>
                    
                </div>
                <div class="message ${img == "gif" ? 'noback' : ''}" style="font-size: ${sty.font}; color:  ${sty.color} !important; background-color:  ${sty.background} !important;">${v.message}</div>
            </div>
        </div>
    </li>
    `);
        //给头像添加点击事件
        $(".c_left .avatar").last().click(function () {
            let name = $(this).parent().find(".u_n").text()


            set.user.clickUserName = $(this).parent().find(".u_n").text()//获取name
            console.log($(this).parent().find(".u_n").text())
            console.log("set.user", set.user)
            sk.emit('socketShake', set.user)

        })
    }

}

new index()


 //向后端发送数据